import { ipcMain, BrowserWindow, Menu, MenuItem } from 'electron'
import { SqlBuilder } from '../db/sqlbuilder'
import { db } from '../db'
import { v4 as uuidv4 } from 'uuid'

/**
 * 判断是否是开发模式
 */
export const isDev = process.env.NODE_ENV === 'development' || !!process.env.VITE_DEV_SERVER_URL

/**
 * 设置所有IPC处理程序
 */
export function setupIpcHandlers() {
  // 窗口控制
  setupWindowHandlers()
  
  // 右键菜单
  setupContextMenuHandlers()
  
  // 笔记本相关
  setupNotebookHandlers()
  
  // 笔记相关
  setupNoteHandlers()
  
  // 标签相关
  setupTagHandlers()
  
  // 设置相关
  setupSettingHandlers()
  
  // 同步相关
  setupSyncHandlers()
}

/**
 * 移除所有IPC处理程序
 */
export function removeIpcHandlers() {
  // 窗口控制
  ipcMain.removeHandler('window:minimize')
  ipcMain.removeHandler('window:maximize')
  ipcMain.removeHandler('window:close')
  ipcMain.removeHandler('window:updateTheme')
  
  // 右键菜单
  ipcMain.removeHandler('context-menu:show')
  
  // 笔记本相关
  ipcMain.removeHandler('notebook:getAll')
  ipcMain.removeHandler('notebook:get')
  ipcMain.removeHandler('notebook:create')
  ipcMain.removeHandler('notebook:update')
  ipcMain.removeHandler('notebook:delete')
  
  // 笔记相关
  ipcMain.removeHandler('note:getAll')
  ipcMain.removeHandler('note:getAllByNotebook')
  ipcMain.removeHandler('note:get')
  ipcMain.removeHandler('note:create')
  ipcMain.removeHandler('note:update')
  ipcMain.removeHandler('note:delete')
  
  // 标签相关
  ipcMain.removeHandler('tag:getAll')
  ipcMain.removeHandler('tag:get')
  ipcMain.removeHandler('tag:create')
  ipcMain.removeHandler('tag:update')
  ipcMain.removeHandler('tag:delete')
  ipcMain.removeHandler('tag:bindNote')
  ipcMain.removeHandler('tag:unbindNote')
  ipcMain.removeHandler('tag:getByNote')
  
  // 设置相关
  ipcMain.removeHandler('settings:getAll')
  ipcMain.removeHandler('settings:get')
  ipcMain.removeHandler('settings:set')
  
  // 同步相关
  ipcMain.removeHandler('sync:getConfigs')
  ipcMain.removeHandler('sync:getConfig')
  ipcMain.removeHandler('sync:saveConfig')
  ipcMain.removeHandler('sync:deleteConfig')
  ipcMain.removeHandler('sync:setActive')
  ipcMain.removeHandler('sync:startSync')
}

// 窗口控制处理程序
function setupWindowHandlers() {
  // 最小化窗口
  ipcMain.handle('window:minimize', () => {
    const win = BrowserWindow.getFocusedWindow();
    if (win) {
      win.minimize();
    }
    return true;
  });

  // 最大化/还原窗口
  ipcMain.handle('window:maximize', () => {
    const win = BrowserWindow.getFocusedWindow();
    if (win) {
      if (win.isMaximized()) {
        win.unmaximize();
        return false;
      } else {
        win.maximize();
        return true;
      }
    }
    return false;
  });

  // 关闭窗口
  ipcMain.handle('window:close', () => {
    const win = BrowserWindow.getFocusedWindow();
    if (win) {
      win.close();
    }
    return true;
  });
  
  // 更新窗口主题
  ipcMain.handle('window:updateTheme', (_, theme: 'light' | 'dark') => {
    const win = BrowserWindow.getFocusedWindow();
    if (win) {
      // 设置透明背景，保持原有符号颜色
      win.setTitleBarOverlay({
        color: 'rgba(0, 0, 0, 0)',
        symbolColor: theme === 'dark' ? '#ffffff' : '#333333',
        height: 30
      });
    }
    return true;
  });
}

// 右键菜单处理程序
function setupContextMenuHandlers() {
  // 显示右键菜单
  ipcMain.handle('context-menu:show', (_, params) => {
    const { menuItems, x, y } = params;
    
    const menu = new Menu();
    
    // 将渲染进程传来的菜单项添加到菜单
    menuItems.forEach((item: { type?: string; label?: string; accelerator?: string; icon?: string; callbackId?: string }) => {
      if (item.type === 'separator') {
        menu.append(new MenuItem({ type: 'separator' }));
      } else {
        menu.append(
          new MenuItem({
            label: item.label,
            accelerator: item.accelerator,
            click: () => {
              // 当用户点击菜单项时，将回调ID发送回渲染进程
              const focusedWindow = BrowserWindow.getFocusedWindow();
              if (focusedWindow && item.callbackId) {
                focusedWindow.webContents.executeJavaScript(
                  `window.elec._contextMenuCallbacks.call("${item.callbackId}");`
                );
              }
            }
          })
        );
      }
    });
    
    // 在主窗口上显示右键菜单
    const focusedWindow = BrowserWindow.getFocusedWindow();
    if (focusedWindow) {
      menu.popup({ 
        window: focusedWindow,
        x: Math.round(x),
        y: Math.round(y)
      });
    }
    
    return true;
  });
}

// 笔记本相关处理程序
function setupNotebookHandlers() {
  // 获取所有笔记本
  ipcMain.handle('notebook:getAll', async () => {
    try {
      const sql = SqlBuilder.forEntity('notebooks')
        .select()
        .eq('is_deleted', 0)
        .orderBy('order_index')
        .build();
      
      return db.prepare(sql.sql).all(sql.params);
    } catch (error) {
      console.error('获取笔记本列表失败:', error);
      throw error;
    }
  });
  
  // 获取指定笔记本
  ipcMain.handle('notebook:get', async (_, id: string) => {
    try {
      const sql = SqlBuilder.forEntity('notebooks')
        .select()
        .eq('id', id)
        .eq('is_deleted', 0)
        .build();
      
      return db.prepare(sql.sql).get(sql.params);
    } catch (error) {
      console.error('获取笔记本详情失败:', error);
      throw error;
    }
  });
  
  // 创建笔记本
  ipcMain.handle('notebook:create', async (_, notebook) => {
    try {
      const notebookWithId = {
        ...notebook,
        id: uuidv4(),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        is_deleted: 0
      };
      
      const sql = SqlBuilder.forEntity('notebooks')
        .insert(notebookWithId)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return notebookWithId;
    } catch (error) {
      console.error('创建笔记本失败:', error);
      throw error;
    }
  });
  
  // 更新笔记本
  ipcMain.handle('notebook:update', async (_, id: string, notebook) => {
    try {
      const updateData = {
        ...notebook,
        updated_at: new Date().toISOString()
      };
      
      const sql = SqlBuilder.forEntity('notebooks')
        .update(updateData)
        .eq('id', id)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { id, ...updateData };
    } catch (error) {
      console.error('更新笔记本失败:', error);
      throw error;
    }
  });
  
  // 删除笔记本（软删除）
  ipcMain.handle('notebook:delete', async (_, id: string) => {
    try {
      const sql = SqlBuilder.forEntity('notebooks')
        .update({ is_deleted: 1, updated_at: new Date().toISOString() })
        .eq('id', id)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { success: true };
    } catch (error) {
      console.error('删除笔记本失败:', error);
      throw error;
    }
  });
}

// 笔记相关处理程序
function setupNoteHandlers() {
  // 获取所有笔记
  ipcMain.handle('note:getAll', async () => {
    try {
      const sql = SqlBuilder.forEntity('notes')
        .select()
        .eq('is_deleted', 0)
        .orderBy('updated_at', 'DESC')
        .build();
      
      return db.prepare(sql.sql).all(sql.params);
    } catch (error) {
      console.error('获取笔记列表失败:', error);
      throw error;
    }
  });
  
  // 获取指定笔记本下的所有笔记
  ipcMain.handle('note:getAllByNotebook', async (_, notebookId: string) => {
    try {
      const sql = SqlBuilder.forEntity('notes')
        .select()
        .eq('notebook_id', notebookId)
        .eq('is_deleted', 0)
        .orderBy('updated_at', 'DESC')
        .build();
      
      return db.prepare(sql.sql).all(sql.params);
    } catch (error) {
      console.error('获取笔记本下的笔记列表失败:', error);
      throw error;
    }
  });
  
  // 获取指定笔记
  ipcMain.handle('note:get', async (_, id: string) => {
    try {
      const sql = SqlBuilder.forEntity('notes')
        .select()
        .eq('id', id)
        .eq('is_deleted', 0)
        .build();
      
      return db.prepare(sql.sql).get(sql.params);
    } catch (error) {
      console.error('获取笔记详情失败:', error);
      throw error;
    }
  });
  
  // 创建笔记
  ipcMain.handle('note:create', async (_, note) => {
    try {
      const noteWithId = {
        ...note,
        id: uuidv4(),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        is_deleted: 0
      };
      
      const sql = SqlBuilder.forEntity('notes')
        .insert(noteWithId)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return noteWithId;
    } catch (error) {
      console.error('创建笔记失败:', error);
      throw error;
    }
  });
  
  // 更新笔记
  ipcMain.handle('note:update', async (_, id: string, note) => {
    try {
      const updateData = {
        ...note,
        updated_at: new Date().toISOString()
      };
      
      const sql = SqlBuilder.forEntity('notes')
        .update(updateData)
        .eq('id', id)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { id, ...updateData };
    } catch (error) {
      console.error('更新笔记失败:', error);
      throw error;
    }
  });
  
  // 删除笔记（软删除）
  ipcMain.handle('note:delete', async (_, id: string) => {
    try {
      const sql = SqlBuilder.forEntity('notes')
        .update({ is_deleted: 1, updated_at: new Date().toISOString() })
        .eq('id', id)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { success: true };
    } catch (error) {
      console.error('删除笔记失败:', error);
      throw error;
    }
  });
}

// 标签相关处理程序
function setupTagHandlers() {
  // 获取所有标签
  ipcMain.handle('tag:getAll', async () => {
    try {
      const sql = SqlBuilder.forEntity('tags')
        .select()
        .eq('is_deleted', 0)
        .orderBy('name')
        .build();
      
      return db.prepare(sql.sql).all(sql.params);
    } catch (error) {
      console.error('获取标签列表失败:', error);
      throw error;
    }
  });
  
  // 获取指定标签
  ipcMain.handle('tag:get', async (_, id: string) => {
    try {
      const sql = SqlBuilder.forEntity('tags')
        .select()
        .eq('id', id)
        .eq('is_deleted', 0)
        .build();
      
      return db.prepare(sql.sql).get(sql.params);
    } catch (error) {
      console.error('获取标签详情失败:', error);
      throw error;
    }
  });
  
  // 创建标签
  ipcMain.handle('tag:create', async (_, tag) => {
    try {
      const tagWithId = {
        ...tag,
        id: uuidv4(),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        is_deleted: 0
      };
      
      const sql = SqlBuilder.forEntity('tags')
        .insert(tagWithId)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return tagWithId;
    } catch (error) {
      console.error('创建标签失败:', error);
      throw error;
    }
  });
  
  // 更新标签
  ipcMain.handle('tag:update', async (_, id: string, tag) => {
    try {
      const updateData = {
        ...tag,
        updated_at: new Date().toISOString()
      };
      
      const sql = SqlBuilder.forEntity('tags')
        .update(updateData)
        .eq('id', id)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { id, ...updateData };
    } catch (error) {
      console.error('更新标签失败:', error);
      throw error;
    }
  });
  
  // 删除标签（软删除）
  ipcMain.handle('tag:delete', async (_, id: string) => {
    try {
      const sql = SqlBuilder.forEntity('tags')
        .update({ is_deleted: 1, updated_at: new Date().toISOString() })
        .eq('id', id)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { success: true };
    } catch (error) {
      console.error('删除标签失败:', error);
      throw error;
    }
  });
  
  // 绑定标签到笔记
  ipcMain.handle('tag:bindNote', async (_, noteId: string, tagId: string) => {
    try {
      // 检查是否已存在
      const existingRecord = db.prepare('SELECT * FROM note_tags WHERE note_id = ? AND tag_id = ? AND is_deleted = 0').get(noteId, tagId);
      
      if (existingRecord) {
        // 已存在且未删除，不需要操作
        return { success: true };
      }
      
      // 检查是否存在被删除的记录
      const deletedRecord = db.prepare('SELECT * FROM note_tags WHERE note_id = ? AND tag_id = ? AND is_deleted = 1').get(noteId, tagId);
      
      if (deletedRecord) {
        // 将已删除记录恢复
        const sql = SqlBuilder.forEntity('note_tags')
          .update({ is_deleted: 0, created_at: new Date().toISOString() })
          .eq('note_id', noteId)
          .eq('tag_id', tagId)
          .build();
        
        db.prepare(sql.sql).run(sql.params);
        return { success: true };
      }
      
      // 创建新记录
      const relation = {
        note_id: noteId,
        tag_id: tagId,
        created_at: new Date().toISOString(),
        is_deleted: 0,
        sync_id: null,
        sync_status: 0,
        sync_time: null
      };
      
      const sql = SqlBuilder.forEntity('note_tags')
        .insert(relation)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { success: true };
    } catch (error) {
      console.error('绑定标签到笔记失败:', error);
      throw error;
    }
  });
  
  // 解绑标签与笔记
  ipcMain.handle('tag:unbindNote', async (_, noteId: string, tagId: string) => {
    try {
      // 软删除
      const sql = SqlBuilder.forEntity('note_tags')
        .update({ is_deleted: 1 })
        .eq('note_id', noteId)
        .eq('tag_id', tagId)
        .build();
      
      db.prepare(sql.sql).run(sql.params);
      return { success: true };
    } catch (error) {
      console.error('解绑标签与笔记失败:', error);
      throw error;
    }
  });
  
  // 获取笔记的所有标签
  ipcMain.handle('tag:getByNote', async (_, noteId: string) => {
    try {
      const query = `
        SELECT t.* FROM tags t
        JOIN note_tags nt ON t.id = nt.tag_id
        WHERE nt.note_id = ? AND nt.is_deleted = 0 AND t.is_deleted = 0
        ORDER BY t.name
      `;
      
      return db.prepare(query).all(noteId);
    } catch (error) {
      console.error('获取笔记的标签列表失败:', error);
      throw error;
    }
  });
}

// 设置相关处理程序
function setupSettingHandlers() {
  // 获取所有设置
  ipcMain.handle('settings:getAll', async () => {
    try {
      const settings = db.prepare('SELECT * FROM settings').all();
      
      // 将设置列表转换为键值对对象
      const settingsObj: Record<string, string> = settings.reduce((obj: Record<string, string>, setting: any) => {
        obj[setting.key] = setting.value;
        return obj;
      }, {});
      
      return settingsObj;
    } catch (error) {
      console.error('获取所有设置失败:', error);
      throw error;
    }
  });
  
  // 获取指定设置
  ipcMain.handle('settings:get', async (_, key: string) => {
    try {
      const setting: any = db.prepare('SELECT * FROM settings WHERE key = ?').get(key);
      return setting ? setting.value : null;
    } catch (error) {
      console.error('获取设置失败:', error);
      throw error;
    }
  });
  
  // 设置设置项
  ipcMain.handle('settings:set', async (_, key: string, value: string) => {
    try {
      // 检查设置是否存在
      const existingSetting = db.prepare('SELECT * FROM settings WHERE key = ?').get(key);
      
      if (existingSetting) {
        // 更新设置
        db.prepare('UPDATE settings SET value = ?, updated_at = ? WHERE key = ?').run(value, new Date().toISOString(), key);
      } else {
        // 插入设置
        db.prepare('INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)').run(key, value, new Date().toISOString());
      }
      
      return { success: true };
    } catch (error) {
      console.error('设置设置项失败:', error);
      throw error;
    }
  });
}

// 同步相关处理程序
function setupSyncHandlers() {
  // 获取所有同步配置
  ipcMain.handle('sync:getConfigs', async () => {
    try {
      return db.prepare('SELECT * FROM sync_config ORDER BY created_at DESC').all();
    } catch (error) {
      console.error('获取同步配置列表失败:', error);
      throw error;
    }
  });
  
  // 获取指定同步配置
  ipcMain.handle('sync:getConfig', async (_, id: number) => {
    try {
      return db.prepare('SELECT * FROM sync_config WHERE id = ?').get(id);
    } catch (error) {
      console.error('获取同步配置详情失败:', error);
      throw error;
    }
  });
  
  // 保存同步配置
  ipcMain.handle('sync:saveConfig', async (_, config) => {
    try {
      const now = new Date().toISOString();
      
      if (config.id) {
        // 更新现有配置
        const sql = SqlBuilder.forEntity('sync_config')
          .update({
            provider: config.provider,
            name: config.name,
            config: JSON.stringify(config.config),
            updated_at: now
          })
          .eq('id', config.id)
          .build();
        
        db.prepare(sql.sql).run(sql.params);
        return { ...config, updated_at: now };
      } else {
        // 创建新配置
        const sql = SqlBuilder.forEntity('sync_config')
          .insert({
            provider: config.provider,
            name: config.name,
            config: JSON.stringify(config.config),
            is_active: false,
            created_at: now,
            updated_at: now
          })
          .build();
        
        const result = db.prepare(sql.sql).run(sql.params);
        return { ...config, id: result.lastInsertRowid, created_at: now, updated_at: now };
      }
    } catch (error) {
      console.error('保存同步配置失败:', error);
      throw error;
    }
  });
  
  // 删除同步配置
  ipcMain.handle('sync:deleteConfig', async (_, id: number) => {
    try {
      db.prepare('DELETE FROM sync_config WHERE id = ?').run(id);
      return { success: true };
    } catch (error) {
      console.error('删除同步配置失败:', error);
      throw error;
    }
  });
  
  // 设置活动同步配置
  ipcMain.handle('sync:setActive', async (_, id: number) => {
    try {
      // 重置所有配置为非活动
      db.prepare('UPDATE sync_config SET is_active = 0').run();
      
      // 设置指定配置为活动
      if (id > 0) {
        db.prepare('UPDATE sync_config SET is_active = 1 WHERE id = ?').run(id);
      }
      
      return { success: true };
    } catch (error) {
      console.error('设置活动同步配置失败:', error);
      throw error;
    }
  });
  
  // 开始同步
  ipcMain.handle('sync:startSync', async () => {
    try {
      // 这里应该实现实际的同步逻辑
      // 基于活动的同步配置来执行同步操作
      
      // 假设同步成功
      return { success: true, message: '同步成功' };
    } catch (error) {
      console.error('同步失败:', error);
      throw error;
    }
  });
}
